package com.dc.chat.app.biz.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dc.chat.app.biz.FriendApplyBiz;
import com.dc.chat.app.biz.FriendBiz;
import com.dc.chat.app.service.mp.FriendApplyService;
import com.dc.chat.app.service.mp.FriendService;
import com.dc.chat.app.service.mp.UserService;
import com.dc.chat.entity.dao.Friend;
import com.dc.chat.entity.dao.FriendApply;
import com.dc.chat.entity.dao.User;
import com.dc.chat.entity.to.ResponseBean;
import com.dc.chat.entity.to.friend.FriendListItem;
import com.dc.chat.interceptor.security.Security;
import com.dc.chat.interceptor.security.SecurityInterceptor;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.xml.ws.Response;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class FriendApplyBizImpl implements FriendApplyBiz {
    @Resource
    FriendApplyService friendApplyService;
    @Resource
    UserService userService;
    @Resource
    RedisTemplate redisTemplate;
    @Resource
    FriendService friendService;
    @Resource
    SimpMessagingTemplate simpMessagingTemplate;
    @Override
    public ResponseBean<Integer> addFriendApply(Integer userId, String context) {
        String username = SecurityInterceptor.threadLocal.get();
        User user = userService.selectByUserName(username);
        if(userId.equals(user.getId())){
            return ResponseBean.failed("不能添加自己为好友");
        }
        User user1 = userService.getById(userId);
        if(user1==null){
            return ResponseBean.failed("用户不存在");
        }
        FriendApply apply = friendApplyService.getBaseMapper().selectOne(
                Wrappers.lambdaQuery(new FriendApply())
                        .eq(FriendApply::getFromUserId, user.getId())
                        .eq(FriendApply::getToUserId, userId)
                        .eq(FriendApply::getStatus, 0)
        );
        Friend one = friendService.getOne(
                Wrappers.lambdaQuery(new Friend())
                        .eq(Friend::getUserId, user.getId())
                        .eq(Friend::getFriendId, userId)
        );
        if(one!=null){
            return ResponseBean.failed("你们已经是好友了");
        }
        if(apply!=null){
            apply.setContext(apply.getContext()+"\n"+context);
            friendApplyService.updateById(apply);
            websocketAddFriendApply(username,user1.getUserName());
            return ResponseBean.success("发送成功",apply.getId());
        }
        FriendApply friendApply=new FriendApply();
        friendApply.setFromUserId(user.getId());
        friendApply.setToUserId(userId);
        friendApply.setStatus(0);
        friendApply.setContext(context);
        friendApply.setCreateTime(LocalDateTime.now());
        friendApplyService.save(friendApply);
        websocketAddFriendApply(username,user1.getUserName());
        return ResponseBean.success("发送成功",friendApply.getId());
    }
    public void websocketAddFriendApply(String fromUsername,String username){
        Map loginUser = redisTemplate.opsForHash().entries("login");
        String token = (String) loginUser.get(username);
        Map map=new HashMap();
        map.put("addFriendApply",true);
        simpMessagingTemplate.convertAndSend("/u/"+token,"用户"+fromUsername+"发来了好友请求",map);
    }

    @Override
    public ResponseBean<List<FriendApply>> getList() {
        String username = SecurityInterceptor.threadLocal.get();
        User user = userService.selectByUserName(username);
        Integer id = user.getId();
        LambdaQueryWrapper<FriendApply> w = Wrappers.lambdaQuery(new FriendApply());
        w.eq(FriendApply::getFromUserId,id).or().eq(FriendApply::getToUserId,id);
        w.orderByDesc(FriendApply::getCreateTime);
        List<FriendApply> friendApplies = friendApplyService.getBaseMapper().selectList(w);
        for (FriendApply friendApply : friendApplies) {
            if(friendApply.getFromUserId().equals(user.getId())) {
                Integer toUserId = friendApply.getToUserId();
                User byId = userService.getById(toUserId);
                friendApply.setUsername(byId.getUserName());
                friendApply.setNickname(byId.getNickName());
                friendApply.setAvatar(byId.getAvatar());
            }
            else{
                Integer fromUserId = friendApply.getFromUserId();
                User byId = userService.getById(fromUserId);
                friendApply.setUsername(byId.getUserName());
                friendApply.setNickname(byId.getNickName());
                friendApply.setAvatar(byId.getAvatar());
            }
        }
        return ResponseBean.success("查询成功",friendApplies);
    }

    @Override
    @Transactional
    public ResponseBean<Integer> agree(Integer id) throws JsonProcessingException {
        String username = SecurityInterceptor.threadLocal.get();
        User user = userService.selectByUserName(username);
        FriendApply friendApply = friendApplyService.getById(id);
        if(friendApply==null){
            return ResponseBean.failed("没有此条记录");
        }
        Integer toUserId = friendApply.getToUserId();
        if(!toUserId.equals(user.getId())){
            return ResponseBean.failed("你无权操作此条记录");
        }
        if(friendApply.getStatus().equals(1)){
            return ResponseBean.failed("你以经同意该条申请");
        }
        if(friendApply.getStatus().equals(2)){
            return ResponseBean.failed("你以经拒绝该条申请");
        }
        //我申请对方的也设置为已同意
        LambdaUpdateWrapper<FriendApply> lambdaUpdateWrapper=new LambdaUpdateWrapper();
        lambdaUpdateWrapper.eq(FriendApply::getFromUserId,user.getId())
                        .eq(FriendApply::getToUserId,friendApply.getFromUserId())
                                .eq(FriendApply::getStatus,0);
        lambdaUpdateWrapper.set(FriendApply::getStatus,1);
        friendApplyService.update(lambdaUpdateWrapper);
        friendApply.setStatus(1);
        friendApplyService.updateById(friendApply);
        //写入到friend表
        Friend friend=new Friend();
        friend.setFriendId(friendApply.getFromUserId());
        friend.setUserId(friendApply.getToUserId());
        friend.setCreateTime(LocalDateTime.now());
        friendService.save(friend);
        friend.setId(null);
        friend.setFriendId(friendApply.getToUserId());
        friend.setUserId(friendApply.getFromUserId());
        friendService.save(friend);
        //websocket发送 已经加上好友  TODO并附带好友信息 和聊天信息
        Integer fromUserId = friendApply.getFromUserId();
        User fromUser = userService.getById(fromUserId);
        String token = (String) redisTemplate.opsForHash().get("login", fromUser.getUserName());
        Map header=new HashMap();
        header.put("tyhy",true);
        //把当前登录用户信息 和消息信息写入头
        FriendListItem friendListItem=new FriendListItem();
        friendListItem.setAvatar(user.getAvatar());
        friendListItem.setBack(null);
        friendListItem.setNickname(user.getNickName());
        friendListItem.setOnline(redisTemplate.opsForHash().get("login",user.getUserName())!=null);
        friendListItem.setUserId(user.getId());
        friendListItem.setUsername(user.getUserName());
        friendListItem.setNoRead(0);
        ObjectMapper objectMapper=new ObjectMapper();
        String friendListItemString = objectMapper.writeValueAsString(friendListItem);
        header.put("friendListItem",friendListItemString);
        simpMessagingTemplate.convertAndSend("/u/"+token,"用户名为"+user.getUserName()+"的用户同意了你的好友申请",header);

        String toToken = (String) redisTemplate.opsForHash().get("login", user.getUserName());

        friendListItem=new FriendListItem();
        friendListItem.setAvatar(fromUser.getAvatar());
        friendListItem.setBack(null);
        friendListItem.setNickname(fromUser.getNickName());
        friendListItem.setOnline(redisTemplate.opsForHash().get("login",fromUser.getUserName())!=null);
        friendListItem.setUserId(fromUser.getId());
        friendListItem.setUsername(fromUser.getUserName());
        friendListItem.setNoRead(0);
       friendListItemString = objectMapper.writeValueAsString(friendListItem);
        header.put("friendListItem",friendListItemString);
        simpMessagingTemplate.convertAndSend("/u/"+toToken,"已同意"+fromUser.getUserName()+"的好友申请",header);
        //更新好友表
        return ResponseBean.success("操作成功",null);
    }

    @Override
    public ResponseBean<Integer> reject(Integer id) {
        String username = SecurityInterceptor.threadLocal.get();
        User user = userService.selectByUserName(username);
        FriendApply byId = friendApplyService.getById(id);
        if(byId==null){
            return ResponseBean.failed("没有此条记录");
        }
        Integer toUserId = byId.getToUserId();
        if(!toUserId.equals(user.getId())){
            return ResponseBean.failed("你无权操作此条记录");
        }
        if(byId.getStatus().equals(1)){
            return ResponseBean.failed("你以经同意该条申请");
        }
        if(byId.getStatus().equals(2)){
            return ResponseBean.failed("你以经拒绝该条申请");
        }
        byId.setStatus(2);
        friendApplyService.updateById(byId);
        //websocket发送 拒绝了你添加
        Integer fromUserId = byId.getFromUserId();
        User fromUser = userService.getById(fromUserId);
        String token = (String) redisTemplate.opsForHash().get("login", fromUser.getUserName());
        Map header=new HashMap();
        header.put("tyhy",true);
        simpMessagingTemplate.convertAndSend("/u/"+token,"用户名为"+user.getUserName()+"的用户拒绝了你的好友申请",header);
        //更新好友表
        return ResponseBean.success("操作成功",null);
    }
}
